<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
    </div>
    
    <!-- 查询条件和操作按钮 -->
    <div class="search-bar">
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="用户名">
          <el-input 
            v-model="queryForm.username" 
            placeholder="请输入用户名" 
            clearable
            style="width: 180px;"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="usersLoading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-left: auto;">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card class="table-card">
      <el-table 
        :data="users" 
        style="width: 100%;" 
        v-loading="usersLoading"
        :height="tableHeight"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          small
        />
      </div>
    </el-card>
    
    <!-- 用户编辑/新增对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      @close="resetForm"
    >
      <el-form 
        ref="userFormRef" 
        :model="userForm" 
        :rules="userFormRules" 
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { getUserList, createUser, updateUser, deleteUser } from '../utils/api'

export default {
  name: 'UserManagement',
  components: {
    Plus,
    Search
  },
  setup() {
    const users = ref([])
    const usersLoading = ref(false)
    const dialogVisible = ref(false)
    const submitLoading = ref(false)
    const isEdit = ref(false)
    const userFormRef = ref()
    
    // 查询表单
    const queryForm = ref({
      username: ''
    })
    
    // 分页数据
    const pagination = ref({
      page: 1,
      size: 10,
      total: 0
    })
    
    // 计算表格高度
    const tableHeight = computed(() => {
      return 'calc(100vh - 284px)'
    })
    
    const userForm = ref({
      id: null,
      username: '',
      password: '',
      email: '',
      status: 1
    })
    
    const userFormRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑用户' : '新增用户'
    })
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      return new Date(dateTime).toLocaleString('zh-CN')
    }
    
    // 加载用户列表
    const loadUsers = async () => {
      usersLoading.value = true
      try {
        const params = {
          page: pagination.value.page,
          size: pagination.value.size
        }
        if (queryForm.value.username) {
          params.username = queryForm.value.username
        }
        
        const response = await getUserList(params)
        if (response.data.code === 200) {
          const data = response.data.data
          users.value = data.records || data
          pagination.value.total = data.total || users.value.length
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('获取用户列表失败')
      } finally {
        usersLoading.value = false
      }
    }
    
    // 查询功能
    const handleSearch = () => {
      pagination.value.page = 1
      loadUsers()
    }
    
    // 重置查询
    const handleReset = () => {
      queryForm.value.username = ''
      pagination.value.page = 1
      loadUsers()
    }
    
    // 分页大小改变
    const handleSizeChange = (newSize) => {
      pagination.value.size = newSize
      pagination.value.page = 1
      loadUsers()
    }
    
    // 当前页改变
    const handleCurrentChange = (newPage) => {
      pagination.value.page = newPage
      loadUsers()
    }
    
    // 新增用户
    const handleAdd = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑用户
    const handleEdit = (row) => {
      isEdit.value = true
      userForm.value = {
        id: row.id,
        username: row.username,
        password: '', // 编辑时不显示原密码
        email: row.email,
        status: row.status
      }
      dialogVisible.value = true
    }
    
    // 删除用户
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(`确定要删除用户 ${row.username} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteUser(row.id)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          loadUsers() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!userFormRef.value) return
      
      try {
        await userFormRef.value.validate()
        submitLoading.value = true
        
        let response
        if (isEdit.value) {
          // 编辑用户
          response = await updateUser(userForm.value.id, userForm.value)
        } else {
          // 新增用户
          response = await createUser(userForm.value)
        }
        
        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          loadUsers() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      userForm.value = {
        id: null,
        username: '',
        password: '',
        email: '',
        status: 1
      }
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
    }
    
    onMounted(() => {
      loadUsers()
    })
    
    return {
      users,
      usersLoading,
      dialogVisible,
      submitLoading,
      userForm,
      userFormRules,
      userFormRef,
      queryForm,
      pagination,
      tableHeight,
      dialogTitle,
      formatDateTime,
      loadUsers,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.page-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 12px;
  flex-shrink: 0;
  height: 32px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.search-bar {
  background: #f8f9fa;
  padding: 8px 16px;
  border-radius: 4px;
  margin-bottom: 12px;
  flex-shrink: 0;
}

.search-form {
  display: flex;
  align-items: center;
  width: 100%;
  margin: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-form .el-form-item:last-child {
  margin-right: 0;
}

.search-form .el-form-item__label {
  font-size: 14px;
  height: 32px;
  line-height: 32px;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin-bottom: 0;
}

.table-card .el-card__body {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.pagination-wrapper {
  margin-top: 12px;
  text-align: right;
  flex-shrink: 0;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
}
</style>